package com.dapeis.web.wx.controller.impl;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ag.utils.json.AGsonBuilder;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.domain.User;
import com.dapeis.service.UserService;
import com.dapeis.web.wx.controller.RestController;

/**
 * 
 * Title:WxOAuth2Controller.java WxOAuth2Controller Description:
 * 
 * @author yuanyong
 * @date 2017年4月18日 下午1:43:43 Email: hzyuanyong@126.com
 *
 */
@Controller
@RequestMapping("/wx/oauth2")
public class WxOAuth2Controller extends RestController {
    @Resource
    WxMpService wxMpService;

    @Resource
    UserService userService;

    @RequestMapping(produces = StylistConstants.ContentType.TEXT_HTML)
    public void execute(HttpSession session, HttpServletRequest request,
	    HttpServletResponse response) throws IOException {
	print(request);
	response.setContentType(StylistConstants.ContentType.TEXT_HTML);
	String code = request.getParameter("code");
	System.out.println("code:" + code);
	try {
	    WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService
		    .oauth2getAccessToken(code);
	    System.out.println("access token:"
		    + wxMpOAuth2AccessToken.toString());

	    WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(
		    wxMpOAuth2AccessToken, null);

	    User user = userService.getUserByWeixinOpenId(wxMpUser.getOpenId());
	    if (null == user) {
		userService.registFromWeixin(wxMpUser.getOpenId(),
			wxMpUser.getNickname(), wxMpUser.getHeadImgUrl(),
			AGsonBuilder.create().toJson(wxMpUser));
	    }

	} catch (WxErrorException e) {
	    e.printStackTrace();
	}

	response.getWriter().flush();
	response.getWriter().close();
    }

}